package com.eregg.learn.netty.protocol.server.handler;

import com.eregg.learn.netty.protocol.protocol.request.LoginRequestPacket;
import com.eregg.learn.netty.protocol.protocol.response.LoginResponsePacket;
import com.eregg.learn.netty.protocol.session.Session;
import com.eregg.learn.netty.protocol.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) throws Exception {

        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        loginResponsePacket.setUserName(loginRequestPacket.getUsername());
        //1.登录校验
        if(valid(loginRequestPacket)){
            loginResponsePacket.setSuccess(true);
            String userId = randomUserId();
            loginResponsePacket.setUserId(userId);
            SessionUtil.bindSession(new Session(userId, loginRequestPacket.getUsername()), ctx.channel());
            System.out.println(String.format("用户[%s]登陆成功", loginRequestPacket.getUsername()));
        }else {
            loginResponsePacket.setSuccess(false);
            loginResponsePacket.setReason("wrong username or password");
            System.out.println(String.format("用户[%s]登陆失败", loginRequestPacket.getUsername()));
        }

        ctx.channel().writeAndFlush(loginResponsePacket);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Session user = SessionUtil.getSession(ctx.channel());
        SessionUtil.unBindSession(ctx.channel());
        System.out.println(String.format("用户[%s]退出成功", user.getUsername()));
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return loginRequestPacket.getUsername().equals(loginRequestPacket.getPassword());
    }

    private static String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }
}
